<?php
namespace app\flash\controller;
use QL\QueryList;
use think\Db;
use think\Controller;
use think\Exception;
use think\Common;
use think\Validate;

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: *");
//header('Access-Control-Allow-Methods: POST,GET','OPTIONS');
header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); //支持的http动作
if($_SERVER['REQUEST_METHOD'] == 'OPTIONS'){
    exit;
}
class Flash extends Controller
{
  /**
   * 功能：采集币世界快讯
   * 时间：2019/08/06
   * 作者：张仕虎
   */
    public function a(){
      $url = 'https://www.bishijie.com/kuaixun.html';
      $rulers = [
          //文章标题
          'article_id' => ['.kuaixun_list ul','data-id'],
        //文章标题
        'title' => ['.kuaixun_list h2 a','text'],
        // //发布日期
        'date' => ['.kuaixun_list ul>span','text'],
        //文字内容
        'content' => ['.kuaixun_list  div>a ','text'],
        'url'    => ['.kuaixun_list ul>li>li>a','href']
      ];
      $data = QueryList::Query($url,$rulers)->data;
      // $arr = [];
      foreach ($data as $key => $value) {
        $search = array(" ","　","\n","\r","\t");
        $replace = array("","","","","");
        $content = str_replace($search,$replace,$value['content']);
        $arr[] = array(
            'article_id' => $value['article_id'],
          'title' => $value['title'],
          'time'  => $value['date'],
          'datetime' => strtotime(date("Y-m-d H:i:s")),
          'details'=>json_encode($content)
        );
        
      }
      $count = count($arr);
      for ($i=0; $i < $count; $i++) {
        //$mysql = Db::name('flashs')->insert($arr[$i],true);
          //判断否存在，不在则插入,存在则更新
          $iscurrency = Db::name('flashs')->where(array('article_id'=>$arr[$i]['article_id']))->find();
          if(empty($iscurrency)){
              //插入
              Db::name('flashs')->insertGetId($arr[$i]);
          }else{
              //更新
              Db::name('flashs')->where(array('article_id'=>$arr[$i]['article_id']))->update($arr[$i]);
          }
      }
    }
    /**
     * 查询快讯采集的最新数据
     * 
     */
    public function poll(){
      $id = input('id');
      if (empty($id)) {
        return json(msg(0,'','参数错误'));
      }
    $data = Db::query("select * from flashs where article_id>$id");
    $count = count($data);
   return json(msg(1,'',$count));
    }
    /**
   * 功能：看空看多的状态改变
   * 时间：2019/08/06
   * 作者：张仕虎
   */
    public function like(){
      $id = input('id');
      $bulish = input('bulish');//看多状态 1-增加 2-减少
      $bearish = input('bearish');//看空状态 1-增加 2-减少
      if (empty($id)) {
        return json(msg(0,'','文章id不存在'));
      }
      if ($bulish==1) {
        $res = Db::table('flashs')->where('id',$id)->setInc('bulish');
    }else if ($bulish==2) {
      $lis = db('flashs')->where('id',$id)->value('bulish');
      if ($lis==0) {
        return json(msg(0,'','看多不能再点了'));
      }
        $res = Db::table('flashs')->where('id',$id)->setDec('bulish');
    }
      if ($bearish==1) {
        $res = Db::table('flashs')->where('id',$id)->setInc('bearish');
      }else if ($bearish==2) {
        $lis = Db::table('flashs')->where('id',$id)->value('bearish');
        if ($lis==0) {
          return json(msg(0,'','看少不能再点了'));
        }
        $res = DB::table('flashs')->where('id',$id)->setDec('bearish');
      }
      if ($res==1) {
        return json(msg(1,'','修改成功'));
      }else{
        return json(nsg(0,'','修改失败'));
      }
      
  }
  /**
   * 功能：快讯查询接口（简易）
   * 时间：2019/08/06
   * 作者：张仕虎
   */
  public function find(){
    $pagesize = input('pagesize')?input('pagesize'):20;
    $page     = input('page')?input('page'):1;
    // $data_count= Db::table('flashs')->count();
    $data = Db::table('flashs')->page($page)->order('article_id desc')->paginate($pagesize,false,['query'=>request()->param()])->each(function($item,$key){
     $item['details'] = \json_decode($item['details'],true);
     $item['datetime']    = date('Y-m-d H:i:s',$item['datetime']);
     //$item['count_data'] = Db::table('comment')->where(['message_id'=>$item['id'],'flag'=>1])->count();
    return $item;
    });
     return json(msg(1,$data,'查询成功'));
  }
  /**
   * 功能：快讯深度的搜索
   * 时间：2019/08/26
   * 作者：张仕虎
   */
  public function search(){
    $search = trim(input('search'));//搜索字段
    $pagesize = input('pagesize')?input('pagesize'):20;
    $page     = input('page')?input('page'):1;
    $where[] = ['title','like',"%$search%"];
    $kuaixun = Db::table('flashs')->where($where)->field('id,title,details,bulish,bearish,time,datetime,article_id,pinglun_no')->order('article_id desc')->page($page)->paginate($pagesize,false,['query'=>request()->param()])->each(function($item,$key){
      $item['details'] = json_decode($item['details'],true);
      $item['datetime']= date('Y-m-d H:i:s',$item['datetime']);
      return $item;
    });
    $shendu  = Db::table('deepness')->where($where)->field('id,title,content,picture,source,time,content_id,pinglun_no')->order('content_id desc')->page($page)->paginate($pagesize,false,['query'=>request()->param()])->each(function($item,$key){
      $item['time'] = date('Y-m-d H:i:s',$item['time']);
      $item['title'] = str_replace('置顶原创','',$item['title']);
      return $item;
    });
    return json(msg(1,['kuaixun'=>$kuaixun,'shendu'=>$shendu]));
    // var_dump($shendu,$kuaixun);
  }

  /**
   * 功能：评论点赞
   * 时间：2019/08/06
   * 作者：张仕虎
   */
  public function likes(){
    $id         = input('id');//评论表ID
    $like_count = input('like_count');//评论状态 1-点赞 2-取消点赞
    $user_id    = input('user_id');//用户id
    $cid        = input('cid');//app软件唯一标识 
    $create_time= strtotime(date('Y-m-d H:i:s'));//创建时间
    if (empty($id)) {
      return json(msg(0,'','id未找到!'));
    }
    if ($like_count==1) {
      if ($user_id) {
        $arr = array(
          'user_id'   => $user_id,
          'comment_id'=> $id,
          'cid'       => $cid,
          'create_time' => $create_time
        );
        $result = Db::table('like')->insert($arr);
        if (!$result) {
          return json(msg(0,'','点赞失败'));
        }
      }  
      $res = Db::table('comment')->where(['id'=>$id,'flag'=>1])->setInc('like_count');
    }else{
      $find = Db::table('comment')->where(['id'=>$id,'flag'=>1])->find();
      if ($find['like_count']==0) {
        return json(msg(0,'','不能再点了！'));
      }
      if ($user_id) {
          $result = Db::table('like')->where(['id'=>$id,'user_id'=>$user_id])->delete();
      }
      $res = Db::table('comment')->where(['id'=>$id,'flag'=>1])->setDec('like_count');
    }
    if ($res) {
      return json(msg(1,'','点赞成功'));
    }else{
      return json(msg(0,'','点赞失败'));
    }
  }

  //评论查询
    public function comments(){
       $data = input('');//
       $id = $data['id'];
       /*$result = db('flashs_comment')
           ->where(array('message_id'=>$id,'parent_id'=>0))
           ->paginate(20,false,['query'=>request()->param()]);
       foreach ($result as $key=>$val){
           //查询所有子级
           var_dump($val);die;
       }*/
//           var_dump($result);die;
        $result =  db('comment')
            ->alias('fc')
            ->join('user u','u.id = fc.from_id','left')
            ->where(['message_id'=>$id,'flag'=>1])
            ->column('fc.id,fc.from_id,fc.message_id,fc.content,parent_id,u.id uid,u.username,u.phone');
        foreach ($result as $key=>$val){
            //查询父级用户信息
            $parent_id = $val['parent_id'];//父级评论的id
            if($parent_id){
                $parent_user_id = db('comment')->where(['id'=>$parent_id,'flag'=>1])->value('from_id');
                $result[$key]['parent_user_id'] = $parent_user_id;
                $parent_user_info = db('user')->where(['id'=>$parent_user_id,'flag'=>1])->field('username,phone')->find();
                $result[$key]['parent_user_name']= $parent_user_info['username'];
                $result[$key]['parent_user_phone']= $parent_user_info['phone'];
            }
        }
        $arr = getTree($result,'parent_id');
        return json(msg(1,$arr,'评论及回复查询成功'));
    }


    public function comments2(){
        $data = input('');//
        $id = $data['id'];
        //评论页码
        $page1 = isset($data['page1'])?$data['page1']:'1';
        //子孙级回复页码
        $page2 = isset($data['page2'])?$data['page2']:'1';
        $result = db('comment')
            ->alias('fc')
            ->join('user u','u.id = fc.from_id','left')
            ->where(array('message_id'=>$id,'parent_id'=>0,'flag'=>1))
            ->field('fc.id,fc.from_id,fc.message_id,fc.content,parent_id,u.id uid,u.username,u.phone')
            ->paginate(20,false,['query'=>request()->param(),'page'=>$page1])->each(function ($item,$key){
                $data = input('');//
                $id = $data['id'];
                $page2 = isset($data['page2'])?$data['page2']:'1';
                $is_zisun = db('comment')->where(array('message_id'=>$id,'parent_id'=>$item['id'],'flag'=>1))->find();
                //是否有子孙
                if($is_zisun){
                    $item['zisun'] = db('comment')
                        ->alias('fc')
                        ->join('user u','u.id = fc.from_id','left')
                        ->field('fc.id,fc.from_id,fc.message_id,fc.content,parent_id,u.id uid,u.username,u.phone')
                        ->where('message_id ='.$id.' and parent_id!=0 and flag=1')
                        ->paginate(20,false,['query'=>request()->param(),'page'=>$page2])->each(function ($item,$key){
                            //查询父级用户信息
                            $parent_id = $item['parent_id'];//父级评论的id
                            if($parent_id){
                                $parent_user_id = db('comment')->where(['id'=>$parent_id,'flag'=>1])->value('from_id');
                                $item['parent_user_id'] = $parent_user_id;
                                $parent_user_info = db('user')->where('id',$parent_user_id)->field('username,phone')->find();
                                $item['parent_user_name']= $parent_user_info['username'];
                                $item['parent_user_phone']= $parent_user_info['phone'];
                            }
                            return $item;
                        });
                }
                return $item;
            });
        return json(msg(1,$result,'评论及回复查询成功'));
    }

    //一级评论
    public function  first_comments(){
        $data = input('');//
        $validate = Validate::make([
            'id'  => 'require',
        ]);
        $res = $validate->check($data);
        if($res !== true){
            return json(msg(0, '', $validate->getError()));
        }
        $id = $data['id'];
        //评论页码
        $result = db('comment')
            ->alias('fc')
            ->join('user u','u.id = fc.from_id','left')
            ->where(array('message_id'=>$id,'parent_id'=>0,'flag'=>1))
            ->field('fc.id,fc.from_id,fc.message_id,fc.content,u.username,u.phone,like_count,u.picture,fc.create_time')
            ->paginate(20,false,['query'=>request()->param()])->each(function ($item,$key){
                $data = input('');//
                $id = $data['id'];
                $item['content'] = json_decode($item['content']);
                //查询回复数
                $zisun = $this->getChildrenIds($item['id']);
                $arr = explode(',',$zisun);
                array_shift($arr);
                $item['reply_count'] = count($arr);
                return $item;
            });
        return json(msg(1,$result,'一级评论查询成功'));
    }

    //子孙评论
    public function zisun_comments(){
        $data = input('');//
        $validate = Validate::make([
            'id'  => 'require',
        ]);
        $res = $validate->check($data);
        if($res !== true){
            return json(msg(0, '', $validate->getError()));
        }
        $id = $data['id'];
        $detail = db('comment')
            ->alias('fc')
            ->join('user u','u.id = fc.from_id','left')
            ->field('fc.id,fc.from_id,fc.message_id,fc.content,u.username,u.phone,like_count,u.picture,fc.create_time')
            ->where(array('fc.id'=>$id,'flag'=>1))
            ->find();
        $zisun = $this->getChildrenIds($detail['id']);
        $arr = explode(',',$zisun);
        array_shift($arr);
        $zisun = db('comment')
            ->alias('fc')
            ->join('user u','u.id = fc.from_id','left')
            ->field('fc.id,fc.from_id,fc.message_id,fc.content,u.username,u.phone,like_count,u.picture,fc.create_time,parent_id')
            ->where(array('fc.id'=>$arr,'flag'=>1))
            ->paginate(20,false,['query'=>request()->param()])->each(function ($item,$key){
                $item['content'] = json_decode($item['content']);
                $data = input('');//
                $id = $data['id'];
                //当不是二级评论时，显示父级信息
                $parent_id = $item['parent_id'];//父级评论的id
                if($parent_id != $id){
                    $parent_user_id = db('comment')->where(['id'=>$parent_id,'flag'=>1])->value('from_id');
                    $item['parent']['parent_user_id'] = $parent_user_id;
                    $parent_user_info = db('user')->where('id',$parent_user_id)->field('username,phone')->find();
                    $item['parent']['parent_user_name']= $parent_user_info['username'];
                    $item['parent']['parent_user_phone']= $parent_user_info['phone'];
                    $parent = db('comment')-> where(array('id'=>$item['parent_id'],'flag'=>1))->find();
                    $item['parent']['parent_user_message'] = json_decode($parent['content']);
                }else{
                    $item['parent'] = null;
                }
                return $item;
            });
        return json(msg(1,compact('detail','zisun'),'子孙评论查询成功'));

    }

    //下级所有id
    function getChildrenIds ($id)
    {
        $ids = '';
        $result =db('comment')->where(array('parent_id'=>$id,'flag'=>1))->select();
        if ($result)
        {
            foreach ($result as $key=>$val)
            {
                $ids .= ','.$val['id'];
                $ids .= $this->getChildrenIds ($val['id']);
            }
        }
        return $ids;
    }
}
